﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml;
using System.Xml.Serialization;

using MASAS.MSM.DomainLayer.Logging;

namespace MASAS.MSM.Common.Symbology
{

    /// <summary>
    /// Symbol Manager.
    /// </summary>
    public class SymbolManager
    {

        // Private members...
        private List< SymbolLibrary > _symLibs;

        /// <summary>
        /// Initializes a new instance of the <see cref="SymbolManager"/> class.
        /// </summary>
        public SymbolManager()
        {
            _symLibs = new List<SymbolLibrary>();

            string path = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetEntryAssembly().Location ) + @"\libraries\Symbols\";

            // Load the Symbols
            // NOTE: This is hardcoded for now, future may 
            //       see a cleaner way of doing this.

            // Load the EMS symbols...
            LoadSymbolLibrary( path + "EmergencyMappingSymbologyLibrary.xml" );
        }

        /// <summary>
        /// Validates the symbol key.
        /// </summary>
        /// <param name="symbolKey">The symbol key.</param>
        /// <returns></returns>
        public string ValidateSymbolKey( string symbolKey )
        {
            string retValue = string.Empty;

            foreach( SymbolLibrary symLib in _symLibs )
            {
                retValue = symLib.ValidateSymbolKey( symbolKey );

                if( retValue != string.Empty )
                {
                    break;
                }
            }

            if( retValue == string.Empty )
            {
                retValue = symbolKey;
            }

            return retValue;
        }

        /// <summary>
        /// Loads the symbol library at the given path.
        /// </summary>
        /// <param name="libraryPath">The library path.</param>
        private void LoadSymbolLibrary( string libraryPath )
        {
            SymbolLibrary symbols       = null;
            XmlSerializer serializer    = new XmlSerializer( typeof( SymbolLibrary ) );

            try
            {
                using( XmlReader reader = XmlReader.Create( libraryPath ) )
                {
                    symbols = ( SymbolLibrary )serializer.Deserialize( reader );
                }
            }
            catch( Exception ex )
            {
                Logger.AddLogEntry( "An unexpected exception has occured!", ex );
            }

            if( symbols != null )
            {
                _symLibs.Add( symbols );
            }
        }

    }

}
